<?php
/**
 * 手动创建上传目录脚本
 * 解决 open_basedir 限制问题
 */

echo "<h2>上传目录创建脚本</h2>\n";

// 获取当前网站根目录
$documentRoot = $_SERVER['DOCUMENT_ROOT'];
echo "网站根目录: $documentRoot<br>\n";

// 需要创建的目录
$directories = [
    '/uploads',
    '/uploads/avatars',
    '/uploads/temp'
];

foreach ($directories as $dir) {
    $fullPath = $documentRoot . $dir;
    
    if (file_exists($fullPath)) {
        echo "✓ 目录已存在: $dir<br>\n";
        
        // 检查权限
        if (is_writable($fullPath)) {
            echo "&nbsp;&nbsp;&nbsp;✓ 目录可写<br>\n";
        } else {
            echo "&nbsp;&nbsp;&nbsp;⚠ 目录不可写，尝试修改权限...<br>\n";
            if (chmod($fullPath, 0755)) {
                echo "&nbsp;&nbsp;&nbsp;✓ 权限修改成功<br>\n";
            } else {
                echo "&nbsp;&nbsp;&nbsp;✗ 权限修改失败<br>\n";
            }
        }
    } else {
        echo "⚠ 目录不存在: $dir，尝试创建...<br>\n";
        
        if (mkdir($fullPath, 0755, true)) {
            echo "&nbsp;&nbsp;&nbsp;✓ 目录创建成功<br>\n";
        } else {
            echo "&nbsp;&nbsp;&nbsp;✗ 目录创建失败<br>\n";
        }
    }
}

echo "<br><h3>.htaccess 文件创建</h3>\n";

// 创建 .htaccess 文件保护上传目录
$htaccessContent = '# 禁止直接访问 PHP 文件
<Files "*.php">
    Order Deny,Allow
    Deny from all
</Files>

# 允许图片文件访问
<FilesMatch "\.(jpg|jpeg|png|gif|webp)$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

# 设置缓存头
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/webp "access plus 1 month"
</IfModule>';

$htaccessFile = $documentRoot . '/uploads/.htaccess';
if (!file_exists($htaccessFile)) {
    if (file_put_contents($htaccessFile, $htaccessContent)) {
        echo "✓ .htaccess 文件创建成功<br>\n";
    } else {
        echo "✗ .htaccess 文件创建失败<br>\n";
    }
} else {
    echo "✓ .htaccess 文件已存在<br>\n";
}

echo "<br><h3>测试文件写入</h3>\n";

// 测试文件写入权限
$testFile = $documentRoot . '/uploads/test_write.txt';
$testContent = 'Test file created at ' . date('Y-m-d H:i:s');

if (file_put_contents($testFile, $testContent)) {
    echo "✓ 文件写入测试成功<br>\n";
    
    // 清理测试文件
    if (unlink($testFile)) {
        echo "✓ 测试文件清理成功<br>\n";
    } else {
        echo "⚠ 测试文件清理失败<br>\n";
    }
} else {
    echo "✗ 文件写入测试失败<br>\n";
}

echo "<br><h3>服务器信息</h3>\n";
echo "PHP版本: " . PHP_VERSION . "<br>\n";
echo "文件上传限制: " . ini_get('upload_max_filesize') . "<br>\n";
echo "POST最大大小: " . ini_get('post_max_size') . "<br>\n";
echo "临时目录: " . sys_get_temp_dir() . "<br>\n";
echo "open_basedir: " . ini_get('open_basedir') . "<br>\n";

echo "<br><div style='background: #d4edda; padding: 1rem; border-radius: 8px; border-left: 4px solid #28a745;'>";
echo "<strong>使用说明:</strong><br>";
echo "1. 运行此脚本后，头像上传功能应该可以正常工作<br>";
echo "2. 如果仍有问题，请检查服务器的文件权限设置<br>";
echo "3. 确保 PHP 有权限写入 /www/wwwroot/nzy.congqian.cn/uploads/ 目录";
echo "</div>";
?>